package gweb

import (
	"net/http"

	"encoding/base64"
	"log"
)

//为Gweb 的每个请求提供一个上下文
type Context struct {
	W      http.ResponseWriter
	R      *http.Request
	Params map[string]string
}

//设置响应头字符串
func (ctx *Context)SetHeader(key, val string, unique bool) {
	if unique {
		ctx.W.Header().Set(key, val)
	} else {
		ctx.W.Header().Add(key, val)
	}
}

//获取请求头 字符串
func (ctx *Context)GetHead(key string) string {
	return ctx.R.Header.Get(key)
}

//3xx跳转
func (ctx *Context)Redirect(code int, url string) {
	//跳转代码
	ctx.SetHeader("location", url, true)
	//写入http 状态码
	ctx.W.WriteHeader(code)
}

//快速获取参数
func (ctx *Context)GetUrl(key string) string {
	return ctx.Params[key]
}

//设置html模板 和数据
func (ctx *Context)Html(tpl string, data map[string]interface{}) {

}

//返回json 数据
func (ctx *Context)Json(data interface{}) {

}

//设置cookie
func (ctx *Context)SetCookie(cookie *http.Cookie) bool {
	ctx.SetHeader("Set-Cookie", cookie.String(), true)
	return true
}

//获取cookie
func (ctx *Context)GetCookie(key string) string {
	if len(ctx.R.Cookies()) == 0 {
		return ""
	}
	for _, v := range ctx.R.Cookies() {
		if v.Name == key {
			b, err := base64.StdEncoding.DecodeString(v.Value)
			if err != nil {
				log.Panicln(err)
			}
			return string(b)
		}
	}
	return ""
}

//删除 cookie
func (ctx *Context)DelCookie(key string) bool {
	for _, v := range ctx.R.Cookies() {
		if v.Name == key {
			v.MaxAge = -1
			return true
		}
	}
	return true
}